/**
 *  JFTSTool - Java Full Text Search tool.
 *  Copyright (C) <2009>  <grupo JFTS>
 *  This program is free software: you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License as published by
 *	the Free Software Foundation, either version 3 of the License, or
 *	(at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.jftstool.fileParserFramework.txtHandler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.jftstool.fileParserFramework.IDocumentHandler;
import org.jftstool.fileParserFramework.contentHandler.XHTMLResultHandler;
import org.jftstool.fileParserFramework.exceptions.DocumentHandlerException;
import org.jftstool.fileParserFramework.metadata.DocumentMetaData;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

/**
 * Parser for TXT documents.
 * @author grupo JFTS
 *
 */
public class TXTHandler implements IDocumentHandler{
	private static final int bufferSize = 4096;

	@Override
	public void getDocument(InputStream is, ContentHandler resultHandler, DocumentMetaData metaData) throws DocumentHandlerException{
		XHTMLResultHandler result = new XHTMLResultHandler(resultHandler, metaData);
	
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		try {
			char[] buffer = new char[bufferSize];			
			
			result.startDocument();
			result.startElement("p");

	        for (int i = br.read(buffer); i != -1; i = br.read(buffer)){
	        	result.characters(buffer, 0, i);
	        }
	        result.endElement("p");
	        result.endDocument();
		}
		catch (IOException e) {
			throw new DocumentHandlerException("Error to read Plain-Text document");
		}
		catch (SAXException e) {
			throw new DocumentHandlerException("Error building resultHandler");
		}
	}
}